<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 广东卓锐软件有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------

namespace app\mill\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\mill\model\TCloud as TCloudModel;
use app\mill\model\Archives as ArchivesModel;
use app\mill\model\Client as ClientModel;
use app\mill\model\Finance as FinanceModel;
use think\Db;

/**
 * T+Cloud控制器
 * @package app\admin\controller
 */
class Tcloud extends Admin
{

    /**
     * 所有批次-物料清单
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function order($role='')
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $this->getMap();
        //$order_pid = input('order_pid');
        //$map[] = ['order_pid','=',$order_pid];
        $map[] = ['archives_status','=',2];
        // 数据列表
        $data_list = Db::name('mill_order')
            ->where($map)
            ->order('id asc')
            ->paginate()
            ->each(function ($v){
                $archvices = ArchivesModel::getOneStat($v['id'],'order_id');
                $v = array_merge($v,$archvices);

                return $v;
            })
        ;

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle("物料清单") // 页面标题
            ->setTableName('mill_order') // 设置表名
            ->hideCheckbox()
            ->setSearchArea([
                ['text:2', 'archives_sn', '工程编号', 'like'],
                ['text:2', 'engineering', '工程名称', 'like'],
            ])
            ->addColumns([ // 批量添加列
                //['id', '序号'],
                ['archives_sn', '档案号'],
                ['order_sn_off', '产品批次'],
                ['engineering', '工程名称'],
                ['number_sum', '产品总量'],
                ['area_sum', '总面积'],
                ['area_ok_sum', '已完成面积'],
                ['area_on_sum', '未完成面积'],
                ['status1', '开平'],
                ['status2', '打磨'],
                ['status3', '折弯'],
                ['status4', '组装'],
                ['status5', '发货'],
                ['status_time', '审核日期','date'],
                ['archives_sign_time', '图纸确认日期','date'],
                //['archives_handle','经办人'],
                ['right_button', '操作', 'btn']
            ])
            ->addRightButton('bomCreate',['title' => '生成物料清单','href' => url('bomCreate',['id' => '__id__']),'class'=>'btn btn-primary disable-dch ajax-get confirm','icon'=>''])
            ->setRowList($data_list) // 设置表格数据
            ->fetch(); // 渲染模板
    }

    /**
     * 所有批次-销售订单
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function orderSale($role='')
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $this->getMap();
        //$order_pid = input('order_pid');
        //$map[] = ['order_pid','=',$order_pid];
        $map[] = ['archives_status','=',2];
        // 数据列表
        $data_list = Db::name('mill_order')
            ->where($map)
            ->order('id asc')
            ->paginate()
            ->each(function ($v){
                $archvices = ArchivesModel::getOneStat($v['id'],'order_id');
                $v = array_merge($v,$archvices);

                return $v;
            })
        ;

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle("物料清单") // 页面标题
            ->setTableName('mill_order') // 设置表名
            ->hideCheckbox()
            ->setSearchArea([
                ['text:2', 'archives_sn', '工程编号', 'like'],
                ['text:2', 'engineering', '工程名称', 'like'],
            ])
            ->addColumns([ // 批量添加列
                //['id', '序号'],
                ['archives_sn', '档案号'],
                ['order_sn_off', '产品批次'],
                ['engineering', '工程名称'],
                ['number_sum', '产品总量'],
                ['area_sum', '总面积'],
                ['area_ok_sum', '已完成面积'],
                ['area_on_sum', '未完成面积'],
                ['status1', '开平'],
                ['status2', '打磨'],
                ['status3', '折弯'],
                ['status4', '组装'],
                ['status5', '发货'],
                ['status_time', '审核日期','date'],
                ['archives_sign_time', '图纸确认日期','date'],
                //['archives_handle','经办人'],
                ['right_button', '操作', 'btn']
            ])
            ->addRightButton('saleOrderCreate',['title' => '生成销售订单','href' => url('saleOrderCreate',['id' => '__id__']),'class'=>'btn btn-primary disable-dch ajax-get confirm','icon'=>''])
            ->setRowList($data_list) // 设置表格数据
            ->fetch(); // 渲染模板
    }

    /**
     * 所有发货单-销货单
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function deliver($address_status = '2',$_show_i = '',$title='发货记录')
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $this->getMap();
        if(!empty($map)){
            foreach ($map as $k=>$v){
                if($v[0] == 'client_id'){
                    $client_id = $v[2];
                    unset($map[$k]);
                }
            }
        }
        if(!empty($client_id)){
            $order_ids = Db::name('mill_order')->where([['client_id','=',$client_id]])->column('pid');
            if(!empty($order_ids)){
                $order_ids = implode(',',array_values($order_ids));
                $map[] = ['a.order_pid','in',$order_ids];
            }
        }
        $map = array_merge($map);
        // 数据列表
        $data_list = Db::name('mill_order_archives_address')
            ->alias('a')
            ->field("a.*")
            ->where($map)
            ->order('a.create_time desc')
            ->paginate()
            ->each(function ($v){

                $order = Db::name('mill_order')
                    ->field('*,group_concat(DISTINCT order_sn) as order_sn,group_concat(DISTINCT batch) as batch,group_concat(DISTINCT order_sn_off) as order_sn_off')
                    ->where([['id','in',$v['order_ids']]])
                    ->find();
                $v['order_sn'] = "{$order['order_sn']}（{$order['batch']}）";
                $v['batch'] = $order['batch'];
                $v['order_sn_off'] = $order['order_sn_off'];
                $v['client_id2'] = $order['client_id'];
                //$v['address_time'] = !empty($v['address_time'])?date('Y-m-d H:i:s',$v['address_time']):'';

                $v['address_sum'] = Db::name('mill_order_archives_give')->where(['address_sn'=>$v['address_sn']])->count('id');

                $v = array_merge($order,$v);

                return $v;
            })
        ;

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle($title) // 页面标题
            ->setTableName('mill_order') // 设置表名
            ->setSearchArea([
                ['text:2', 'a.address_sn', '发货单号', 'like'],
                ['select:3', 'client_id', '客户公司','','',ClientModel::getList('company')],
                ['text:2', 'a.archives_sns', '工程号', 'like'],
                //['text:2', 'o.engineering', '工程名称', 'like'],
                ['daterange:2', 'a.create_time', '发货日期'],
            ])
            ->hideCheckbox()
            ->addColumns([ // 批量添加列
                ['car_plate_number', '车牌号码'],
                ['address_sn', '发货单号'],
                ['create_time', '发货时间','datetime'],
                ['client_id2','客户公司','','',ClientModel::getList('company')],
                ['order_sn', '工程号'],
                ['address_sum', '产品总数量'],
                ['engineering', '工程名称'],
                ['order_sn_off', '批次'],
                //['give_sum','总数量'],
                //['give_sum4','已发货'],
                //['give_sum0_4','未发货'],
                ['right_button', '操作', 'btn']
            ])
            ->addRightButton('deliverShow',['title' => '查看详情','href' => url('mill/order/deliverShow'.$_show_i,['id'=>'__id__','address_sn' => '__address_sn__','is_price'=>1]),'class'=>'btn btn-default disable-dch','icon'=>''])
            ->addRightButton('deliverShow2',['title' => '导出发货单','href' => url('mill/order/deliverShow'.$_show_i,['id'=>'__id__','address_sn' => '__address_sn__','is_price'=>1,'print'=>'2']),'class'=>'btn btn-default disable-dch','icon'=>'','target'=>'_blank'])
            ->addRightButton('archivesPriceList',['title' => '面积表计价','href' => url('mill/finance/archivespricelist',['address_sn' => '__address_sn__']),'class'=>'btn btn-primary disable-dch','icon'=>''],['area' => ['98%', '98%'], 'title' => ['面积表计价', 'font-size:24px;text-align: center;']])
            ->addRightButton('saleDeliveryCreate',['title' => '生成销货单','href' => url('saleDeliveryCreate',['id' => '__id__']),'class'=>'btn btn-primary disable-dch ajax-get confirm','icon'=>''])

            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'address_date'  => 60,
                'archives_sn'  => 120,
                'engineering'  => 150,
                'batch'  => 80,
                'give_sum'  => 60,
                'give_sum4'  => 60,
                'give_sum0_4'  => 60,
                'right_button'  => 60,
            ])
            ->fetch(); // 渲染模板
    }

    //创建物料清单
    public function bomCreate(){

        $id = input('id');
        $order = Db::name('mill_order')->where(['id'=>$id])->find();
        $order['row_area'] = Db::name('mill_order_archives')->where(['order_id'=>$order['id']])->sum('row_area');
        if(empty($order['row_area']))$this->error('未上传面积表');

        $order['lists'] = Db::name('mill_order_archives')->field('*,ROUND(one_area,4) as one_area')->where(['order_id'=>$order['id']])->order('id asc')->select();

        //录入前先查询物料清单是否存在
        $re = TCloudModel::bomQuery($order);
        if(!empty($re))$this->error("[{$order['archives_sn']}]物料清单已存在，请前往T+查看");
        //录入档案号
        TCloudModel::archivesCreate($order['archives_sn']);

        //录入库存
        $re = TCloudModel::inventoryCreateBatch($order['lists']);
        foreach ($re['Data'] as $v){
            //部分库存录入失败
            if($v['Success'] == false && strpos($v['ErrMessage'],'不唯一') === false)$this->error("库存录入失败,编号[{$v['Data']['Code']}]数据格式错误");
        }

        //录入物料清单
        TCloudModel::bomCreate($order);

        //自动审核物料清单
        TCloudModel::bomAudit($order);

        //更新状态 0:待上传T+Cloud 1:已上传物料清单 2:已上传销售订单 3:已上传销售出库单 4:已上传形态转换单 5:已上传销货单
        Db::name('mill_order')->where(['id'=>$id])->update(['tcloud_status'=>1]);

        $this->success('创建物料清单成功');

    }

    //创建销售订单
    public function saleOrderCreate(){

        $id = input('id');
        $order = Db::name('mill_order')->where(['id'=>$id])->find();
        $company = Db::name('mill_client')->where(['id'=>$order['client_id']])->find();
        $order['company_code'] = $company['tcloud_company_code'];
        $order['sales_code'] = $company['tcloud_sales_code'];
        $order['row_area'] = Db::name('mill_order_archives')->where(['order_id'=>$order['id']])->sum('row_area');

        $order['lists'] = Db::name('mill_order_archives')->where(['order_id'=>$order['id']])->order('id asc')->select();

        //录入前先查询物料清单是否存在
        $re = TCloudModel::bomQuery($order);
        if(empty($re))$this->error("[{$order['archives_sn']}]物料清单未创建，请联系设计部");

        //获取T+的项目编号
        $project = TCloudModel::getProject($order['order_sn']);
        //录入项目
        if(empty($project))TCloudModel::projectCreate($order);
        //更换为T+的项目编号
        elseif(!empty($project[0]['Code']))$order['order_sn'] = $project[0]['Code'];

        //录入来往单位
        if(empty($company['tcloud_company_code']) || 1==1){
            $partner = TCloudModel::getPartner($company['company']);
            if(empty($partner)){
                //设置来往单位编码
                $company['company_code'] = $order['company_code'] = "HYC{$company['id']}";
                TCloudModel::partnerCreate($company);
                //$partner = TCloudModel::getPartner($company['company']);
            }
            else $order['company_code'] = $partner[0]['Code'];
            //更新来往单位编码
            Db::name('mill_client')->where(['id'=>$company['id']])->update(['tcloud_company_code'=>$order['company_code']]);
        }

        //录入业务员
        if(empty($company['tcloud_sales_code'])){
            $sales = TCloudModel::getPerson($company['sales']);
            if(empty($sales)){
                //设置业务员编码
                $company['sales_code'] = $order['sales_code'] = "HYS{$company['id']}";
                TCloudModel::personCreate($company);
                //$sales = TCloudModel::getPerson($company['sales']);
            }
            else $order['sales_code'] = $sales[0]['Code'];
            //更新业务员编码
            Db::name('mill_client')->where(['id'=>$company['id']])->update(['tcloud_sales_code'=>$order['sales_code']]);
        }

        //录入销售订单
        $re = TCloudModel::saleOrderCreate($order);
        if(!empty($re['code']) && $re['code'] == 999)$this->error("[{$order['archives_sn']}]销售订单已存在，请前往T+查看");
        elseif (!empty($re['message']))$this->error($re['message']);
        //存储销售订单ID，用作关联其他单据
        //if(!empty($re['data']['ID']))Db::name('mill_order')->where(['id'=>$id])->update(['tcloud_sale_order_id'=>$re['data']['ID']]);

        //更新状态 0:待上传T+Cloud 1:已上传物料清单 2:已上传销售单 3:已上传销售出库单 4:已上传形态转换单 5:已上传销货单
        Db::name('mill_order')->where(['id'=>$id])->update(['tcloud_status'=>2]);

        $this->success('创建销售订单成功');

    }

    //创建销货单
    public function saleDeliveryCreate(){

        $id = input('id');
        $address = Db::name('mill_order_archives_address')->where(['id'=>$id])->find();
        $order_ids = $address['order_ids'];
        $order_ids_arr = explode(',',$order_ids);
        $is_price = Db::name('mill_order_archives_initial_price')->where([['order_id','in',$order_ids]])->count('DISTINCT order_id');
        if(empty($is_price) || $is_price != count($order_ids_arr))$this->error('面积表未计价');

        $order = Db::name('mill_order')->where([['id','=',$order_ids_arr[0]]])->find();
        $company = Db::name('mill_client')->where(['id'=>$order['client_id']])->find();
        $address['order_sn'] = $order['order_sn'];
        $address['company_code'] = $company['tcloud_company_code'];
        $address['sales_code'] = $company['tcloud_sales_code'];

        //录入前先查询销货单是否存在
        $re = TCloudModel::saleDeliveryQuery($address);
        if(strtolower($re['message']) == 'ok')$this->error("[{$address['address_sn']}]销货单已存在，请前往T+查看");

        //获取T+的项目编号
        $project = TCloudModel::getProject($order['order_sn']);
        //录入项目
        if(empty($project))TCloudModel::projectCreate($order);
        //更换为T+的项目编号
        elseif(!empty($project[0]['Code']))$order['order_sn'] = $project[0]['Code'];

        //获取发货单产品明细
        $where[] = ['g.address_sn','=',$address['address_sn']];
        $group = 'a.id';
        $join = [['mill_order_archives_give g','a.id=g.archives_id','left'],['mill_order o','a.order_id=o.id','left']];
        $address['lists'] = ArchivesModel::getList(null,"a.*,a.id as archives_id,(COUNT(g.id)*FORMAT(a.one_area,4)) as row_area,(COUNT(g.id)*FORMAT(a.weld,4)) as weld,(COUNT(g.id)*FORMAT(a.slot,4)) as slot",'a.order_id asc,CONVERT (REPLACE(a.sort,\'#\',\'999999\'),signed) ASC',$group,$join,$where);

        //焊缝，刨槽，做合计并添加上去
        $weld = $slot = [
            'archives_sn'   =>  '',//档案号，传空值
            'row_area'      =>  0,//总数
            'price'         =>  0,//单价
            'price_sum'     =>  0,//总价
        ];
        $weld['model'] = '焊缝';//焊缝
        $weld['model_sn'] = '00990005';//去T+平台查询（焊缝）编号
        $slot['model'] = '刨槽';//刨槽
        $slot['model_sn'] = '00990004';//去T+平台查询（刨槽）编号
        foreach ($address['lists'] as &$v){
            //获取单价
            $prices_arr = FinanceModel::getPriceInfo($v);
            $v['price'] = !empty($prices_arr['price'])?floatval($v['price']):0;
            //焊缝单价
            $weld_price = Db::name('mill_order_archives_initial_price')
                ->where(['type'=>1,'order_id'=>$v['order_id']])
                ->value('price');
            $weld_price = floatval($weld_price);
            //刨槽单价
            $slot_price = Db::name('mill_order_archives_initial_price')
                ->where(['type'=>2,'order_id'=>$v['order_id']])
                ->value('price');
            $slot_price = floatval($slot_price);

            //焊缝，刨槽，做合计并添加上去
            $weld['row_area'] += $v['weld'];
            $slot['row_area'] += $v['slot'];

            $weld['price_sum'] += ($v['weld']*$weld_price);
            $slot['price_sum'] += ($v['slot']*$slot_price);
        }

        //额外插入焊缝计价
        if($weld['row_area']){
            $weld['price'] = $weld['price_sum']/$weld['row_area'];
            //保留两位小数，向上进1
            //$weld['price'] = ceil($weld['price']*100)/100;

            $address['lists'][] = $weld;
        }
        //额外插入刨槽计价
        if($slot['row_area']){
            $slot['price'] = $slot['price_sum']/$slot['row_area'];
            //保留两位小数，向上进1
            //$slot['price'] = ceil($slot['price']*100)/100;

            $address['lists'][] = $slot;
        }

        /*//查询销售订单
        $sale_order = TCloudModel::saleOrderQuery($order);
        //销售订单子明细列表
        $order['sale_order_details_list'] = [];

        if(!empty($sale_order['data']['SaleOrderDetails'])){
            foreach ($sale_order['data']['SaleOrderDetails'] as $vv){
                $order['sale_order_details_list'][$vv['Inventory']['Code']] = $vv['ID'];
            }
        }*/

        //录入销货单
        TCloudModel::saleDeliveryCreate($address);

        //更新状态 0:待上传T+Cloud 1:已上传物料清单 2:已上传销售单 3:已上传销售出库单 4:已上传形态转换单 5:已上传销货单
        Db::name('mill_order')->where(['id'=>$id])->update(['tcloud_status'=>5]);

        $this->success('创建销售订单成功');

    }


}
